package main

import (
	"AcsGo/adpter"
	"AcsGo/config"
	"AcsGo/logger"
	"bufio"
	"net"
	"strings"
)

var lg = logger.InitLog()

func main() {

	// 指定服务器监听的端口
	// port := ":8080"
	port := config.LoadServer()
	// 创建TCP监听器
	listener, err := net.Listen("tcp", port)
	if err != nil {
		lg.Fatalf("Error listening on port %s: %v", port, err)
	}
	defer listener.Close()

	lg.Debugf("Server started. Listening on port %s...", port)

	// 循环接受客户端连接
	for {
		// 接受一个客户端连接
		conn, err := listener.Accept()
		if err != nil {
			lg.Debugf("Error accepting connection: %v", err)
			continue
		}

		// 处理客户端连接
		go handleClient(conn)
	}
}

// handleClient 处理与客户端的交互
func handleClient(conn net.Conn) {
	defer conn.Close()

	// 创建一个bufio.Reader，用于从连接中读取数据
	reader := bufio.NewReader(conn)
	clientAddr := conn.RemoteAddr().String()
	lg.Debugf("Client %s connected.", clientAddr)

	// 不断读取客户端发送的消息
	for {
		// 读取客户端发送的一行数据
		msg, err := reader.ReadString('\n')
		if err != nil {
			lg.Debugf("Error reading from client %s: %v", clientAddr, err)
			break
		}

		// 输出接收到的消息
		lg.Debugf("Received from %s: %s", clientAddr, msg)

		// 去除消息两端的空白字符
		msg = strings.TrimSpace(msg)
		// 如果客户端发送的是"exit"，则关闭连接
		if msg == "exit" {
			lg.Debugf("Client %s requested to exit.", clientAddr)
			break
		}

		if msg == "" {
			lg.Debugf("Client %s sent empty message.", clientAddr)
			break
		}

		response, err := adpter.ProcessInput(msg)
		if err != nil {
			lg.Debugf("Error processing input: %v", err)
			// response = "941AY3AZFDFA"
		}
		response += "\r\n"
		lg.Debugf("Sending response to %s: %s", clientAddr, response)
		// 回复客户端消息
		_, err = conn.Write([]byte(response))
		if err != nil {
			lg.Debugf("Error writing to client %s: %v", clientAddr, err)
			break
		}
	}

	lg.Debugf("Client %s disconnected.", clientAddr)
}
